/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imageuploader;

import imageuploader.core.*;
import imageuploader.ui.*;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;


/**
 *
 * @author nir
 */
public class Main {

    static ImageHostingService current = null;
    static ArrayList<ImageHostingService> list;
    static JTextField usernameField = new JTextField();
    static JPasswordField pwdField = new JPasswordField();
    static ImagesPanel photoViewer = new ImagesPanel();
    static JComboBox albums = new JComboBox();
    static JProgressBar progressBar = new JProgressBar();
    
    static{
        Properties services = new Properties();
        try{
            InputStream is = ClassLoader.getSystemResourceAsStream("imageuploader/services.properties");
            services.load(is);
        
        
            Enumeration<Object> elements = services.elements();
            String element;
            ImageHostingService serv;
            Class servClass;
            Properties servProps;
            list = new ArrayList<ImageHostingService>();
            while(elements.hasMoreElements()){
                element = (String)elements.nextElement();
                servProps = new Properties();
                servProps.load(ClassLoader.getSystemResourceAsStream(element));
                servClass = Class.forName(servProps.getProperty("type")) ;
                serv = (ImageHostingService)servClass.getConstructors()[0].newInstance(servProps);
                
                addEventsListeners(serv);
                
                list.add(serv);
            }
        }catch(Exception ex){
            ex.printStackTrace();
            System.exit(0);
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //final ImagesPanel photoViewer = new ImagesPanel();
        final JFrame frm = new JFrame();
        final JScrollPane photoViewerScroller = new JScrollPane(),
                foldersScroller = new JScrollPane();
        final Dimension defSize = new Dimension(950,440);
        final JSplitPane mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        final JPanel sideBar = new JPanel();
        final JPanel statusBar = new JPanel();
        final FileTree folders = new FileTree();
        
        progressBar.setVisible(false);
        statusBar.add(progressBar);
        
        statusBar.setPreferredSize(new Dimension(defSize.width, 30));
        
        foldersScroller.getViewport().add(folders);        
        
        foldersScroller.setPreferredSize(new Dimension(190, 366));

        sideBar.setLayout(new BoxLayout(sideBar, BoxLayout.Y_AXIS));
        sideBar.add(foldersScroller);
        sideBar.setSize(new Dimension(190, 400));
        sideBar.add(createForm());
        sideBar.add(createLoginPanel());
        
        photoViewerScroller.setSize(new Dimension(550,400));
        //photoViewerScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        photoViewerScroller.getViewport().add(photoViewer);
        
        Dimension thumbSize = photoViewer.getThumbSize(),
                    scrollSize = photoViewerScroller.getVerticalScrollBar().getSize();
        
        frm.setPreferredSize(defSize);
        photoViewerScroller.setMinimumSize(new Dimension(thumbSize.width+scrollSize.width+37,  thumbSize.height+37));
        //photoViewerScroller.setPreferredSize(new Dimension(thumbSize.width*6+scrollSize.width+37, defSize.height+37));
        //photoViewerScroller.setMaximumSize(new Dimension(thumbSize.width*4+scrollSize.width+37, defSize.height+37));
        photoViewer.setBackground(Color.WHITE);
        
        frm.addWindowListener(new java.awt.event.WindowAdapter(){
            @Override
            public void windowClosing(java.awt.event.WindowEvent e){
                System.exit(0);
            }        
        });
        
        folders.addTreeSelectionListener(new TreeSelectionListener(){
            public void valueChanged(TreeSelectionEvent event){
                    DefaultMutableTreeNode node = folders.getTreeNode(event.getPath());
                    final FileNode fnode = folders.getFileNode(node);
                    if (fnode != null){
                        
                            new Thread(){
                                public void run(){
                                    try{
                                        photoViewer.showImages(fnode.getFile());
                                    }catch(Exception ex){
                                        ex.printStackTrace();
                                    }
                                }
                                
                            }.start();
                        
                    }
                }
        });
        
        photoViewerScroller.getViewport().addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent event){
                
                int scrollBarWidth = photoViewerScroller.getVerticalScrollBar().getSize().width,
                    tmbWidth = photoViewer.getThumbSize().width,
                    frmWidth = photoViewerScroller.getSize().width,
                    nColumns = photoViewer.getColumns();
                
                photoViewer.resizeColumns(frmWidth, scrollBarWidth, tmbWidth, nColumns);
            }
            
        });           
        
        
        
        mainPane.setLeftComponent(photoViewerScroller);
        mainPane.setRightComponent(sideBar);
        
        mainPane.setDividerLocation(559);
        mainPane.setDividerSize(3);
        Container cp = frm.getContentPane();
        cp.setLayout(new BoxLayout(cp, BoxLayout.PAGE_AXIS));
        cp.add(mainPane);
        cp.add(statusBar);
        frm.pack();
        frm.setVisible(true);
      
        
        
    }

    public static JPanel createForm(){
        JPanel form = new JPanel();
        JButton uploadBtn = new JButton("upload");
        
        uploadBtn.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent arg0) {
                if(current!=null){
                    new Thread(){
                        @Override
                        public void run(){
                            try{
                                File[] files = photoViewer.getChosenFiles();
                                progressBar.setVisible(true);
                                progressBar.setMaximum(files.length);
                                progressBar.setMinimum(0);
                                progressBar.setStringPainted(true);
                                System.out.println("Start Uploading");
                                current.upload(files);
                                System.out.println("End Uploading");
                            }catch(Exception ex){
                                ex.printStackTrace();
                            }
                        }
                    }.start();
                }
            }
        
        });
        
        albums.setSize(new Dimension(50, 25));
        albums.addItemListener(new ItemListener(){

            public void itemStateChanged(ItemEvent event){
                String albumName = (String)event.getItem();
                System.out.println(albumName);
                if(current!=null) current.setAlbum(albumName.equals("")?null:albumName);
            }
        
        });
        form.add(createServicesComboBox());
        form.add(albums);
        form.add(uploadBtn);
        
        return form;
    }
    
    public static JComboBox createServicesComboBox(){
        JComboBox cb = new JComboBox();
        
        Iterator<ImageHostingService> iter = list.iterator();
        cb.addItem("");
        while(iter.hasNext()){
            cb.addItem(iter.next());
        }
        
        cb.addItemListener(new ItemListener(){

            public void itemStateChanged(ItemEvent event) {
                if(event.getStateChange() == ItemEvent.SELECTED){
                    Object item = event.getItem();
                    if(item instanceof ImageHostingService){
                        current = (ImageHostingService)item;
                        new Thread(){
                            @Override
                            public void run() {
                                loginToService(current);
                            }                            
                        }.start();
                    }
                }
            }
            
        });
        
        return cb;
    }
    
    
   public static void loginToService(ImageHostingService service){
        usernameField.setEnabled(false);
        pwdField.setEnabled(false);
        try{
            service.login(usernameField.getText(), new String(pwdField.getPassword()));
            System.out.println("Login succeed");
            HashMap<String, String> albumsList = service.getAlbumList();
            Iterator iter = albumsList.keySet().iterator();
            String key;
            albums.removeAllItems();
            albums.addItem("");
            while(iter.hasNext()){
                key = (String)iter.next();
                albums.addItem(albumsList.get(key));
            }
            current = service;
        }catch(ImageUploaderException ex){
            current = null;
            ex.printStackTrace();
        }finally{
            usernameField.setEnabled(true);
            pwdField.setEnabled(true);                                
        }                          
   }
    
    public static JPanel createLoginPanel(){
        JPanel form = new JPanel();
        GridLayout layout = new GridLayout(2, 2, 0, 0);
        form.setLayout(layout);
        form.add(new JLabel("Username: "));
        form.add( usernameField);
        form.add(new JLabel("Password: "));
        form.add( pwdField );        
        
        return form;
    }

    private static void addEventsListeners(ImageHostingService serv) {
        final BaseImageHostingServiceImpl service = (BaseImageHostingServiceImpl)serv;
        service.events.addEventListener("fileUploaded", new CustomEventListener(){
            
            public void handle() {
                int value = progressBar.getMaximum()-service.getUploadLength();
                System.out.println(value);
                progressBar.setValue(value);
            }
        });
        
        service.events.addEventListener("finishUpload", new CustomEventListener() {

            public void handle() {
                progressBar.setVisible(false);
            }
        });
    }
    
}
